package com.gcloud.api.config;

import com.gcloud.api.ApiRole;
import com.gcloud.common.util.StringUtils;
import com.gcloud.core.exception.GCloudException;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.context.annotation.Configuration;

import javax.annotation.PostConstruct;
/**
Copyright (c) [2020] [G-CLOUD TECHNOLOGY] [G-Cloud 8.0] is licensed under the Mulan PSL v1.
You can use this software according to the terms and conditions of the Mulan PSL v1. You may obtain
a copy of Mulan PSL v1 at: http://license.coscl.org.cn/MulanPSL THIS SOFTWARE IS PROVIDED ON AN 
"AS IS" BASIS, WITHOUT WARRANTIES OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED 
TO NON-INFRINGEMENT, MERCHANTABILITY OR FIT FOR A PARTICULAR PURPOSE. See the Mulan PSL v1 for more details.
 */
@Configuration
public class ApiRoleConfig {

    @Value("${"+ ApiRole.CONFIG_KEY + "}")
    private String roles;

    @Value("${gcloud.api.region:}")
    private String region;

    @PostConstruct
    public void init(){

        boolean controllerApi = false;

        if(StringUtils.isBlank(roles)){
            throw new GCloudException(String.format("::%s not set", ApiRole.CONFIG_KEY));
        }

        String[] configRoles = roles.split(",");
        for(String role : configRoles){
            if(!ApiRole.ROLES.contains(role)){
                throw new GCloudException(String.format("::not support role : %s", role));
            }
            if(ApiRole.CONTROLLER_API.equals(role)){
                controllerApi = true;
            }
        }

        if(controllerApi && StringUtils.isBlank(region)){
            throw new GCloudException(String.format("::api region not set"));
        }


    }

}